<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>图片二维码识别</title>
		<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
		<script src="https://xiaoshan223.gitee.io/web-tools/qrCode/jsQR.js"></script>
	</head>
	<body>
		<div>
			<h2>选择图片base64获取信息</h2>
			<input type="file" value=""  id="pictureChange">
		</div>

		<div>
			<h2>网络地址获取信息</h2>
			<input type="text" style="width: 400px;" id="pictureUrl" placeholder="二维码网络地址或base64图片data"><button onclick="imgUrlToqR()">获取图片信息</button>
		</div>

		<div>
			<h2>识别结果：</h2>
			<ul id="result">
			</ul>
		</div>
	</body>
	<script type="text/javascript">
		$("body").append('<canvas id="qrcanvas" style="display:none;"></canvas>')
		$("#pictureChange").change(function (e) {
			var file = e.target.files[0];
			if(window.FileReader) {
				var fr = new FileReader();
				fr.readAsDataURL(file);
				fr.onloadend = function(e) {
					var base64Data = e.target.result;
					base64ToqR(base64Data)
				}
			}
		})
		function base64ToqR(data) {
			var c = document.getElementById("qrcanvas");
			var ctx = c.getContext("2d");
	
			var img = new Image();
			img.src = data;
			img.onload = function() {
				$("#qrcanvas").attr("width",img.width)
				$("#qrcanvas").attr("height",img.height)
				ctx.drawImage(img, 0, 0, img.width, img.height);
				var imageData = ctx.getImageData(0, 0, img.width, img.height);
				const code = jsQR(imageData.data, imageData.width, imageData.height, {
					inversionAttempts: "dontInvert",
				});
				if(code){
					showCode(code.data)
				}else{
					alert("识别错误")
				}
			};
		}
		
		function imgUrlToqR(url) {
			if(!url){
				url = $("#pictureUrl").val();
			}
			var c = document.getElementById("qrcanvas");
			var ctx = c.getContext("2d");

			var img = new Image();
			//解决跨域问题  ，并图片服务允许跨域访问
			img.crossOrigin = "Anonymous";
			img.src = url;
			img.onload = function() {
				$("#qrcanvas").attr("width",img.width)
				$("#qrcanvas").attr("height",img.height)
				ctx.drawImage(img, 0, 0, img.width, img.height);
				var imageData = ctx.getImageData(0, 0, img.width, img.height);
				const code = jsQR(imageData.data, imageData.width, imageData.height, {
					inversionAttempts: "dontInvert",
				});
				if(code){
					showCode(code.data)
				}else{
					alert("识别错误")
				}
			};
		}
		function showCode(code){
			$("#result").html("<li>"+code+"</li>")
		}
	</script>
</html>